package cn.kgc.controller;

import cn.kgc.mapper.UserMapper;
import cn.kgc.pojo.User;
import cn.kgc.service.UserService;
import cn.kgc.util.Page;
import cn.kgc.validate.userInsert;
import com.alibaba.fastjson.JSON;
import org.aspectj.util.FileUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.annotation.Resource;
import javax.annotation.Resources;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @描述
 * @author：LY
 * @2018/11/1 19:53
 */
@Controller
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 登录
     * @param usercode
     * @param userpassword
     * @param request
     * @return 页面名称
     */
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public String login(String usercode,String userpassword,HttpServletRequest request){
        User user = userService.loginSelect(usercode,userpassword);
        if(user==null){
            request.getSession().setAttribute("errorer","用户名密码错误");
            return "redirect:logg";
        }
        request.getSession().setAttribute("userLogin",user);
        return "frame";
    }


    /**
     * 模糊查询
     * @param user
     * @param pageNum
     * @param request
     * @return 页面名称
     */
    @RequestMapping("query")
    public String query(User user,String pageNum,HttpServletRequest request){
        Page<User> page = userService.userInfo(user,pageNum);
        request.getSession().setAttribute("page",page);
        return "userlist";
    }


    /*@ExceptionHandler({ArithmeticException.class,ClassNotFoundException.class})
    public String exception(HttpServletRequest request,Exception e){
        request.setAttribute("errorMessage",e.getMessage());
        return "error";
    }
*/

    /**
     * 跳转添加页面
     * @return 页面名字
     */
   /* @RequestMapping("addJump")
    public String addJump(){
        return "useradd";
    }*/

    /**
     * 添加操作
     * @param user
     * @param
     * @param
     * @return 页面名字
     */
    /*@RequestMapping("add")
    public String add(@Valid User user, BindingResult bindingResult, Model model){
            if(bindingResult.hasErrors()){
                model.addAttribute("user",user);
                model.addAttribute("error",bindingResult.getAllErrors());
                return "useradd";
            }
            userService.insert(user);
            return "redirect:query";
    }*/


    @RequestMapping(value = "add",method = RequestMethod.GET)
    public String add(@ModelAttribute("user") User user){
        return "useradd";
    }

    @RequestMapping(value = "add",method = RequestMethod.POST)
    public String add(@Validated(userInsert.class) User user, BindingResult result,
                      @RequestParam("fileupload")MultipartFile fileupload,
                      @RequestParam("fileuploads")MultipartFile fileuploads,HttpServletRequest request) throws IOException {


        if(result.hasErrors()){
            return "useradd";
        }
        String path = request.getSession().getServletContext().getRealPath("/upload");

        if(!fileupload.isEmpty()){
            fileupload.transferTo(new File(path+File.separator+UUID.randomUUID()+fileupload.getOriginalFilename()));
        }
        if(!fileuploads.isEmpty()){
            fileuploads.transferTo(new File(path+File.separator+UUID.randomUUID()+fileuploads.getOriginalFilename()));
        }

        /*for (MultipartFile multipartFile:fileuploads) {
            if(!fileupload.isEmpty()){
                multipartFile.transferTo(new File(path+File.separator+UUID.randomUUID()+multipartFile.getOriginalFilename()));
            }
        }*/

        userService.insert(user);
        return "redirect:query";
    }


    /**
     * 删除操作
     * @param id
     * @return 页面名称
     */
    @RequestMapping("delete/{id}")
    public String delete(@PathVariable("id") String id){
        boolean num = userService.deleteByID(id);
        System.out.println(num);
        return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/query";
    }


    @RequestMapping(value = "update/{id}",method = RequestMethod.GET)
    public String update(@PathVariable("id") String id,HttpServletRequest request){
        User user = userService.selectByID(id);
        request.getSession().setAttribute("updateUser",user);
        return "usermodify";

    }


    @RequestMapping("updateOperation")
    public String updateOperation(@Valid User user,BindingResult result,HttpServletRequest request){
        if(result.hasErrors()){
            System.out.println(user);
            request.getSession().setAttribute("updateUser",user);
            request.getSession().setAttribute("error",result.getAllErrors());
            return "usermodify";
        }
        boolean b = userService.updateByID(user);
        return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"query";
    }

    /**
     * 撤销退出
     * @return 登录界面
     */
    @RequestMapping("exit")
    public String exit(HttpServletRequest request){
        request.getSession().removeAttribute("userLogin");
        return "redirect:/logg";
    }



    @RequestMapping(value = "seeview"/*,produces = "application/json;charset=utf-8"*/)
    public @ResponseBody User seeview(@RequestParam String id){
        System.out.println(id);
        User user = userService.selectByID(id);
        System.out.println(user);
        return user;
    }


    @RequestMapping(value = "checkName/{username}")
    public @ResponseBody Object checkName(@PathVariable("username") String username){
        User user = userService.ajaxName(username);
        return JSON.toJSONString(user);
    }




}
